// pages/movies/movies.js
import Util from '../../util/util';

const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    inTheaters: {},
    comingSoon: {},
    top250: {},
    searchResult: {},
    containerShow: true,
    searchPanelShow: false
  },
  onMoreTap(e){
    //console.log(e.currentTarget.dataset.key)
    wx.navigateTo({
      url:'moreMovies/moreMovies?category='+e.currentTarget.dataset.key
    })
  },
  onGirdTap(e){
    //console.log(e);
    wx.navigateTo({
      url:'movieDetail/movieDetail?id='+e.currentTarget.dataset.id
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
   let inTheaters = `${app.globalData.doubanBase}/v2/movie/in_theaters?start=0&count=3`;
   let comingSoon = `${app.globalData.doubanBase}/v2/movie/coming_soon?start=0&count=3`;
   let top250 = `${app.globalData.doubanBase}/v2/movie/top250?start=0&count=3`;
   let util = new Util();
   let request = {
      inTheaters,comingSoon,top250
   }
   function entries(obj) {
     let arr = [];
     for (let key of Object.keys(obj)) {
       arr.push([key, obj[key]]);
     }
     return arr;
   }

   for(let [key,val] of entries(request)){
      new Promise((resolve,reject)=>{
        util.getMoviesData(val,key,resolve);
      })
      .then(res=>{
          let result = util.processDoubanData(res.data,key);
          this.setData({
            [key]:{
              infos:result.infos,
              categoryTitle:result.categoryTitle,
              key:result.key
           }
         });
      })
   }
   
  },
  onCancelImgTap: function (event) {
      this.setData({
        containerShow: true,
        searchPanelShow: false,
        searchResult:{}
      }
    )
  },

  onBindFocus: function (event) {
    this.setData({
      containerShow: false,
      searchPanelShow: true
    })
  },

  onBindBlur: function (event) {
    var text = event.detail.value;
    var searchUrl = app.globalData.doubanBase + "/v2/movie/search?q=" + text;
    var util = new Util();
    new Promise((resolve,reject)=>{
      util.getMoviesData(searchUrl,'',resolve);
    })
    .then(res=>{
        let result = util.processDoubanData(res.data,'');
        console.log(result.infos);
        this.setData({
          searchResult:result.infos
       });
    })
  },
  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },
 
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})